package com.ruoyi.common.security.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * @ClassName AESEncryptUtils
 * @Author samula
 * @Descripe product by com.doctcloud
 * @Data 2025-09-18 12:26
 **/
public class AESEncryptUtils {
    private static final String SECRET_KEY = "https://www.doctcloud.com"; // 你的密钥原文
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    public static String decrypt(String encryptedPassword) throws Exception {
        // Validate input
        if (encryptedPassword == null || encryptedPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("Encrypted password cannot be empty");
        }
        try {
            // 1. Decode Base64
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPassword);

            // 2. Process key consistently with frontend
            byte[] keyBytes = processKey(SECRET_KEY);
            System.out.println("Decrypt key bytes: " + Arrays.toString(keyBytes));
            // 3. Validate key length
            if (keyBytes.length != 16) {
                throw new IllegalArgumentException("Invalid key length after processing: " + keyBytes.length);
            }

            // 4. Initialize cipher
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // 5. Decrypt
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);

        } catch (javax.crypto.BadPaddingException e) {
            // Most common cause: key mismatch or data corruption
            throw new Exception("Decryption failed - bad key or corrupted data", e);
        } catch (Exception e) {
            throw new Exception("Decryption error: " + e.getMessage(), e);
        }
    }

    private static byte[] processKey(String key) {
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        // Ensure exactly 16 bytes for AES-128
        return Arrays.copyOf(keyBytes, 16);
    }

}
